package com.cp.admin.core.listener;

import com.cp.admin.core.util.OnlineUserMap;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @author cj
 * @create 2019-03-20 12:11
 **/
@WebListener
public class LoginListener implements HttpSessionAttributeListener,HttpSessionListener {
    //session添加属性时触发，调用添加方法，将登录添加至在线列表
    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("---add session");
        String username = httpSessionBindingEvent.getName();
        if (username == "cpUser")
        {
            new OnlineUserMap().addOnLine(httpSessionBindingEvent.getSession());
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("---attributeRemoved");
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
        System.out.println("---attributeReplaced");
    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        System.out.println("---sessionCreated");
    }
    //session移除属性时触发，调用移除方法，将登录踢出在线列表
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        System.out.println("---Destroyed session");
        String sessionid = httpSessionEvent.getSession().getId();
        new  OnlineUserMap().removeOnLine(sessionid);
    }
}